package com.lepu.app.fun.grow;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Handler;
import android.os.Message;

import com.app.application.MyApplication;
import com.app.utils.Setting;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.lepu.app.fun.grow.bean.PhotoItem;
import com.lepu.app.usercenter.bean.LoginInfo;

/*
 * 云端同步上传图片
 */
public class GrowImageManager implements AsyncRequest {

	private static final String REQUEST_UPLOAD_IMAGE = "request_upload_image";

	private ArrayList<PhotoItem> mDataList = null;
	private int mCurrentIndex = 0;

	private static GrowImageManager mInstance = null;
	private LoginInfo mLoginInfo = MyApplication.getInstance().getLoginInfo();

	public boolean mIsUploading = false;

	private int mCurrentItemId = 0;

	private int mTotalCount = 0;
	private int mFailCount = 0;

	public static GrowImageManager getInstance() {
		if (mInstance == null) {
			mInstance = new GrowImageManager();
		}

		return mInstance;
	}

	public void destroy() {
		mInstance = null;

		mIsUploading = false;
		LogUtilBase.LogD(null, "取消云端同步上传图片");
	}

	public void init() {

		mDataList = PhotoItem.getAllPhotosNoUpdate(mLoginInfo.UserID);

		if (mDataList != null) {
			LogUtilBase
					.LogD(null, String.format("需要上传%d张图片", mDataList.size()));
			mTotalCount = mDataList.size();
		}
	}
	
	public static final int MSG_UPLOAD_SUCCESS = 10;
	
	Handler mHandler = new Handler(){
		public void handleMessage(Message msg) {
			
			switch (msg.what) {
			case MSG_UPLOAD_SUCCESS:
				
				int successCount = mTotalCount - mFailCount;
				UIHelper.showToast(MyApplication.getInstance(), String.format(
						"您有%d条数据同步成功,%d数据同步失败", successCount, mFailCount));
				destroy();
				
				break;

			default:
				break;
			}
		};
	};

	public void uploadImageContent() {

		if (mInstance == null) {
			return;
		}

		if (mDataList == null || mDataList.size() == 0) {
			LogUtilBase.LogD(null, "未初始化数据，或者没有可上传数据");
			
			return;
		}

		mIsUploading = true;

		if (mCurrentIndex <= mDataList.size() - 1) {
			PhotoItem item = mDataList.get(mCurrentIndex);

			mCurrentItemId = item.id;

			Map<String, File> fileMap = new HashMap<String, File>();
			fileMap.put("Photo", new File(item.imagePath));

			Map<String, Object> map = new HashMap<String, Object>();
			JSONObject params = new JSONObject();
			try {
				params.put("DeviceID", Setting.DEVICEID);
				params.put("ApplicationID", Setting.APPLICATIONID);

				params.put("UserID", mLoginInfo.UserID);
				params.put("LoginToken", mLoginInfo.LoginToken);

				if (item.modifyState == PhotoItem.MODIFY_YES) {
					params.put("PhotoID", item.pictureId);// 修改
				}
				params.put("TakePictureDate", item.addTime);
				params.put("NativePhotoID", mCurrentItemId);
				params.put("Description", item.desc);
				// params.put("Description",
				// EncodeBase64.encode(item.desc.getBytes()));
			} catch (Exception e) {
				e.printStackTrace();
			}
			map.put("ht", params);

			String url = Setting.getAddPhotoUrl();
			if (item.modifyState == PhotoItem.MODIFY_YES) {
				url = Setting.getModifyPhotoUrl();// 修改
			}

			mCurrentIndex++;

			ApiClient.http_post(url, map, fileMap, this, REQUEST_UPLOAD_IMAGE,
					false);
		} else {
			LogUtilBase.LogD(null, "云端同步，上传图片成功");

			mHandler.sendEmptyMessage(MSG_UPLOAD_SUCCESS);
			
		}
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_UPLOAD_IMAGE)) {
			boolean flag = false;
			try {
				JSONObject jsonObject = new JSONObject((String) data);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				JSONObject obj2 = (JSONObject) obj1.get("DetailInfo");

				int PhotoID = obj2.optInt("PhotoID");// 服务器返回需要保存的id
				// int NativePhotoID = obj2.optInt("NativePhotoID");//
				// 本地数据库唯一id对应
				// String PhotoUrl = obj2.optString("PhotoUrl");

				flag = PhotoItem.updatePhotoItemSyncById(mLoginInfo.UserID,
						mCurrentItemId, PhotoID);

			} catch (JSONException e) {
				e.printStackTrace();
			}

			LogUtilBase.LogD(null, String.format(
					"RequestComplete 第%d张图片上传结果==%s", mCurrentIndex,
					String.valueOf(flag)));

			uploadImageContent();
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_UPLOAD_IMAGE)) {
			LogUtilBase.LogD(null, String.format("RequestError 第%d张图片上传结果==%s",
					mCurrentIndex, String.valueOf(false)));

			mFailCount++;
			uploadImageContent();
		}
	}
}